﻿using Flurl.Http;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using TiaoTiaoCode.AutoUpdate.Common.Dtos;
using TiaoTiaoCode.AutoUpdate.ServerUI.Biz;
using TiaoTiaoCode.AutoUpdate.ServerUI.Views;
using TiaoTiaoCode.Common.Helpers;

namespace TiaoTiaoCode.AutoUpdate.ServerUI.ViewModels
{
    /// <summary>
    /// 主程序管理
    /// </summary>
    public class MainProgramManagerViewModel : BindableBase
    {
        #region 字段

        const string AppListApi = "api/ServerUI/appList";

        const string CreateApi = "api/ServerUI/createProgram";

        readonly TiaoTiaoIniFile _iniFile;

        readonly IDialogService _dialogSer;

        #endregion

        #region 属性

        private ObservableCollection<MainProgramView> programs = default!;

        /// <summary>
        /// 主程序列表
        /// </summary>
        public ObservableCollection<MainProgramView> Programs
        {
            get { return programs; }
            set { SetProperty(ref programs, value); }
        }

        #endregion

        #region 命令

        ICommand? createCommand;

        /// <summary>
        /// 创建程序
        /// </summary>
        public ICommand CreateCommand => createCommand ?? (createCommand = new DelegateCommand(CreateProgram));

        #endregion

        public MainProgramManagerViewModel(IDialogService dialogService)
        {
            _dialogSer = dialogService;

            _iniFile = new TiaoTiaoIniFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "setting.ini"));

            QueryAll();
        }

        #region 命令实现

        /// <summary>
        /// 获取应用程序列表
        /// </summary>
        void CreateProgram()
        {
            _dialogSer.ShowDialog(nameof(MainProgramCreateView), DialogCallback);
        }

        /// <summary>
        /// 添加程序信息弹窗回调
        /// </summary>
        /// <param name="dr"></param>
        async void DialogCallback(IDialogResult dr)
        {
            if (dr.Result != ButtonResult.OK) return;

            var baseApi = _iniFile.Read("application", "baseApi", String.Empty);
            var url = $"{baseApi.TrimEnd('/')}/{CreateApi}";

            var ps = dr.Parameters;
            var pn = ps.GetValue<string>("ProgramName");
            var fd = ps.GetValue<string>("Catalog");

            var dto = new MainProgramCreateDto
            {
                ProgramName = pn,
                FilePath = fd
            };

            await url.PostJsonAsync(dto);

            QueryAll();
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        async void QueryAll()
        {
            var lst = await AppListBiz.QueryAll();

            Programs = new ObservableCollection<MainProgramView>(lst);
        }
        #endregion
    }
}
